/**
 * 
 * 对象类工具集合
 * 
 * 1.深复制对象
 * 2.浅复制对象
 * 3.以数组形式返回对象属性集合
 * 
 **/
package com.hdit.utils
{
	import mx.utils.ObjectUtil;
	
	import org.as3commons.reflect.Accessor;
	import org.as3commons.reflect.Field;
	import org.as3commons.reflect.Type;
	import org.as3commons.reflect.Variable;

	public class ObjectUtils
	{
		/***
		 深度clone某个对象，包含Vector 和 Array
		 **/
		public static function deepClone(_obj:*):*
		{
			var returnCloneObj:*;
			var objType:Type=Type.forInstance(_obj);

			if (_obj is Vector.<*> || _obj is Array)
			{
				returnCloneObj=new objType.clazz();
				for each (var eachCloneObj:* in _obj)
				{
					returnCloneObj.push(shadowClone(eachCloneObj));
				}
			}
			else
			{
				returnCloneObj=shadowClone(_obj);
			}
			return returnCloneObj;
		}

		/**
		 * clone 只能clone简单对象的所有的public属性
		 */
		public static function shadowClone(_obj:*):*
		{ 
			var objType:Type=Type.forInstance(_obj);
			var cloneObj:*=new objType.clazz();
			for each (var field:Field in objType.properties)
			{
				if (field is Variable || field is Accessor && Accessor(field).writeable && field.name != 'prototype')
				{
					cloneObj[field.name]=_obj[field.name];
				}
			}
			return cloneObj;
		}
        
        /**
        * 遍历对象属性 返回该对象下所有属性
        * 
        * @param ref  
        * @return       该对象下属性集合
        * **/
        public static function getObjectAllProperty(ref:Object):Array
        {
            var attributes:Array=[];
            var classInfo:Object=ObjectUtil.getClassInfo(ref);
            var qNames:Array=classInfo["properties"];
            var length:int=qNames.length;
            for (var i:int; i < length; i++)
            {
                attributes.push((qNames[i] as QName).localName);
            }
            return attributes;
        }
		
		/**
		 * 复制简单对象
		 * @param sourceObj 被复制的原对象
		 * @param newObj    复制到新对象
		 **/
		public static function cloneSimpleObject(sourceObj:Object,newObj:*):void
		{
			var properties:Array=getObjectAllProperty(sourceObj);
			for (var i:int = 0; i < properties.length; i++) 
			{
				var propertyName:String=properties[i];
				if(newObj.hasOwnProperty(propertyName))
					newObj[propertyName]=sourceObj[propertyName];
			}
			
		}
	}
}
